//
//  WowThirdPartyAppSwitchStrategy.m
//  PersonalOCTest
//
//  Created by zlf on 2025/8/20.
//

#import "WowThirdPartyAppSwitchStrategy.h"

@implementation WowThirdPartyAppSwitchStrategy

- (BOOL)canHandleTag:(WowNotificationSwitchTag)tag {
    // 第三方应用使用特殊的tag规则：section * 100
    return tag >= 100 && tag % 100 == 0;
}

- (void)handleSwitchWithContext:(WowSwitchContext *)context {
    UISwitch *sender = context.sender;
    WowNotifiSetToDeviceManager *manager = context.manager;
    
    // 1. 设备连接检查
//    if (![manager handleSwitchAction:sender]) {
//        return;
//    }
    
    // 2. 计算section
    NSInteger section = sender.tag / 100;
    NSInteger appIndex = section - 1;
    
    // 3. 验证索引
//    if (appIndex < 0 || appIndex >= context.tableViewModel.thirdPartyApp.count) {
//        return;
//    }
//    
//    // 4. 获取应用模型
//    WowAllAppSetInfoModel *model = context.tableViewModel.thirdPartyApp[appIndex];
    
    // 5. 记录操作到队列（用于回滚）
    BOOL oldValue = !sender.isOn;
    NSString *identifier = [NSString stringWithFormat:@"thirdPartyApp_%ld", (long)appIndex];
//    [manager.switchOperationQueue enqueueOperationWithIdentifier:identifier
//                                                        oldValue:oldValue
//                                                        newValue:sender.isOn
//                                                          target:sender];
    
    // 6. 更新本地状态
//    model.setting.syncEnabled = sender.isOn;
//    
//    // 7. 发送设备命令
//    [manager appSet:NO
//                row:appIndex
//        syncEnabled:sender.isOn ? @YES : @NO
//           callback:^(NSDictionary *param) {
//        [self handleCallbackResult:param context:context];
//    }];
    
    // 8. 更新计数和UI
    [self updateAppCountWithContext:context];
    
    // 9. 刷新特定section
    if ([context.viewController respondsToSelector:@selector(tableView)]) {
        UITableView *tableView = [context.viewController performSelector:@selector(tableView)];
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section]
                 withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)updateAppCountWithContext:(WowSwitchContext *)context {
    // 重新计算允许的应用数量
    NSInteger allowedCount = 0;
//    for (WowAllAppSetInfoModel *model in context.tableViewModel.thirdPartyApp) {
//        if (model.setting.syncEnabled) {
//            allowedCount++;
//        }
//    }
//    context.tableViewModel.thirdPartyAppAllowCount = [NSString stringWithFormat:@"%ld", allowedCount];
}

- (void)handleCallbackResult:(NSDictionary *)param context:(WowSwitchContext *)context {
    NSNumber *code = param[@"code"];
    if (code && code.integerValue != 1) {
        NSLog(@"Third party app switch operation failed with code: %@", code);
    }
}

- (NSInteger)priority { return 3; }

- (NSString *)strategyDescription { return @"第三方应用开关策略"; }

@end
